import json
import re


def extract_json_data(response_text):
    """
    从响应文本中提取并解析第一个有效的 JSON 对象。

    :param response_text: 大模型返回的文本
    :return: 解析得到的 JSON 数据字典，或 None 如果解析失败
    """
    try:
        start_index = response_text.find("{")
        end_index = response_text.rfind("}")

        if start_index != -1 and end_index != -1:
            json_str = response_text[start_index:end_index + 1].replace("NA", "null")
            # 去除无效的转义字符
            json_str = re.sub(r'\\[^"\\/bfnrtu]', lambda m: m.group(0)[1:], json_str)

            try:
                data = json.loads(json_str)
                return data
            except json.JSONDecodeError as e:
                print(f"JSON decoding failed: {e}")
    except Exception as e:
        print(f"Unexpected error while extracting JSON data: {e}")

    return None


def escape_markdown_special_chars(value):
    if isinstance(value, str):
        # 先处理特定的字符序列
        value = value.replace('\r<br>\r<br>', '\n').replace('\r', '').replace('<br>', '\n')

        # 然后转义Markdown中的特殊字符，比如竖线和反斜杠
        value = value.replace('\\', '\\\\').replace('|', '\\|').replace('\n', '<br>')
    return value

def generate_markdown_table(items):
    markdown_lines = []
    headers_written = False

    for item in items:
        item_dict = {}
        for field in item._meta.fields + item._meta.many_to_many:
            field_name = field.verbose_name or field.name
            if field.is_relation:
                related_objects = getattr(item, field.name)
                if field.many_to_many:
                    # 对于多对多关系，显示ID和值
                    item_dict[field_name] = "; ".join(
                        [f"{related_object.id} ({str(related_object)})"
                         for related_object in related_objects.all()]
                    )
                else:
                    if related_objects is not None:
                        # 对于普通外键，显示ID和值
                        item_dict[field_name] = f"{related_objects.id} ({str(related_objects)})"
                    else:
                        item_dict[field_name] = "NA"
            else:
                value = getattr(item, field.name)
                if value is None:  # 判断值是否为 None，而不是 0
                    item_dict[field_name] = "NA"
                else:
                    item_dict[field_name] = escape_markdown_special_chars(value)

        if not headers_written:
            headers = list(item_dict.keys())
            header_line = '| ' + ' | '.join(headers) + ' |'
            separator_line = '| ' + ' | '.join(['---'] * len(headers)) + ' |'
            markdown_lines.append(header_line)
            markdown_lines.append(separator_line)
            headers_written = True

        values = list(item_dict.values())
        value_line = '| ' + ' | '.join(map(str, values)) + ' |'
        markdown_lines.append(value_line)
        # print(markdown_lines)

    return "<!-- TABLE_START -->\n" + "\n".join(markdown_lines) + "\n<!-- TABLE_END -->\n"



def extract_report_from_response(response_text):
    """
    从响应文本中提取格式化的报告数据。

    :param response_text: 大模型返回的文本
    :return: 符合格式的 JSON 数据字典，或 None 如果不符合要求
    """
    data = extract_json_data(response_text)

    if data:
        # 检查是否包含所需的字段及其正确的数据类型
        required_fields = {
            "title": str,
            "report_type": str,
            "summary": str,
            "content": str,
            "is_reviewed": bool
        }

        if all(field in data and isinstance(data[field], field_type) for field, field_type in required_fields.items()):
            return data

        print("未匹配到报告数据。")

    return None
